<template>
  <div >
    <div style="display: flex; justify-content: center; align-items: center;">
      <el-input v-model="name" placeholder="请输入物品名" suffix-icon="el-icon-search" style="width: 200px;"
                @keyup.enter.native="loadPost"></el-input>
      <el-select v-model="storage" placeholder="请选择仓库" style="margin-left: 5px;">
        <el-option
            v-for="item in storageData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="goodstype" placeholder="请选择分类" style="margin-left: 5px;">
        <el-option
            v-for="item in goodstypeData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 5px;" @click="loadPost" >查询</el-button>
      <el-button type="success" @click="resetParam" >重置</el-button>
      <el-button type="primary" style="margin-left: 5px;" @click="add" v-if="user.roleId!=2">新增</el-button>
      <el-button type="primary" style="margin-left: 5px;" @click="inGoods"
                 v-if="user.roleId!=2">入库</el-button>
      <el-button type="primary" style="margin-left: 5px;" @click="outGoods"
                 v-if="user.roleId!=2">出库</el-button>
    </div>
    <div>
      <el-table :data="tableData" :header-cell-style="{background:'#f2f5fc',color:'#555555'}"
                border
                highlight-current-row
                @current-change="selectCurrentChange">
        <!--                      配置highlight-current-row 单选-->
        <el-table-column prop="id" label="ID" width="60">
        </el-table-column>
        <el-table-column prop="name" label="物品名" width="180">
        </el-table-column>
        <el-table-column prop="storage" label="仓库" width="180" :formatter="formatStorage">
        </el-table-column>
        <el-table-column prop="goodstype" label="分类" width="180" :formatter="formatGoodstype">
        </el-table-column>
        <el-table-column prop="count" label="数量" width="180">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="250px">
        </el-table-column>
        <el-table-column prop="operate" label="操作" width="160px">
          <template slot-scope="scope">
            <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
            <el-popconfirm
                title="确定删除吗？"
                @confirm="del(scope.row.id)"
                style="margin-left: 5px;">
              <el-button slot="reference" size="small" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog
        title="物品维护"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>

      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="物品名" prop="name">
          <el-col :span="20">
            <el-input v-model="form.name"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="仓库" prop="storage">
          <el-col :span="20">
            <el-select v-model="form.storage" placeholder="请选择仓库" style="margin-left: 5px;">
              <el-option
                  v-for="item in storageData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="分类" prop="goodstype">
          <el-col :span="20">
            <el-select v-model="form.goodstype" placeholder="请选择分类" style="margin-left: 5px;">
              <el-option
                  v-for="item in goodstypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="form.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark" >
          <el-col :span="20">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="出入库"
        :visible.sync="inOrOutDialogVisible"
        width="30%"
        center>

      <el-dialog
          width="75%"
          title="用户选择"
          :visible.sync="innerVisible"
          append-to-body>
        <SelectUser @doSelectUser="doSelectUser"></SelectUser>
        <span slot="footer" class="dialog-footer">
                    <el-button @click="innerVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmUser">确 定</el-button>
                  </span>
      </el-dialog>

      <el-form ref="formInOrOut" :rules="rulesInOrOut"  :model="formInOrOut" label-width="80px">
        <el-form-item label="物品名" prop="goodsname" >
          <el-col :span="20">
            <el-input v-model="formInOrOut.goodsname" ></el-input>
          </el-col>
        </el-form-item>
<!--        :disabled="disabled"，不知道为什么突然用不了-->
<!--        readonly，只读,但是偶尔卡顿 -->
        <el-form-item label="申请人" prop="username">
          <el-col :span="20">
            <el-input v-model="formInOrOut.username" @click.native="selectUser"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="formInOrOut.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="formInOrOut.remark"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button @click="inOrOutDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doInOrOutGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectUser from "@/components/user/SelectUser.vue";

export default {
  name: "GoodsManage",
  components: {SelectUser},
  data() {
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('数量输入过大'));
      } else {
        callback();
      }
    };
    return {
      max_outNum:0,
      disabled_goods:false,
      user: JSON.parse(sessionStorage.getItem('CurUser')),
      storageData:[],
      goodstypeData:[],
      tableData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      name: '',
      storage: '',
      goodstype: '',
      centerDialogVisible: false,
      inOrOutDialogVisible: false,
      innerVisible:false,
      currentRow:{},
      tempUser: {},
      form: {
        id: '',
        name: '',
        storage: '',
        goodstype: '',
        count: '',
        remark: ''
      },
      formInOrOut: {
        goods: '',
        goodsname: '',
        count: '',
        username: '',
        userid: '',
        adminId: '',
        remark: '',
        action:''
      },
      rulesInOrOut:{
        goodsname:[
          {required: true, message: '请输入商品名', trigger: 'blur'}
        ],
        username:[
          {required: true, message: '请选择申请人', trigger: 'blur'}
        ],
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: "blur"},
          {validator: checkCount, trigger: 'blur'}
        ]
      },
      rules: {
        name: [
          {required: true, message: '请输入商品名', trigger: 'blur'}
        ],
        storage: [
          {required: true, message: '请选择仓库', trigger: 'blur'}
        ],
        goodstype: [
          {required: true, message: '请选择分类', trigger: 'blur'}
        ],
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: "blur"},
          {validator: checkCount, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    doSelectUser(val){
      console.log(val);
      this.tempUser=val;
    },
    confirmUser() {
      this.formInOrOut.username = this.tempUser.name
      this.formInOrOut.userid = this.tempUser.id

      this.innerVisible = false
    },
    selectUser() {
      this.innerVisible = true
    },
    selectCurrentChange(val) {
      this.currentRow = val;
    },
    formatStorage(row) {
      let temp = this.storageData.find(item => {
        return item.id == row.storage
      })
      return temp && temp.name
      // 在找到对应项（即 temp 不为 null 或 undefined）的情况下，返回该项的 name 属性，否则返回 undefined。
    },
    formatGoodstype(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id == row.goodstype
      })
      return temp && temp.name
    },
    resetForm() {
      this.$refs.form.resetFields();
      // 真正少了的部分在这里
      this.form.id = '';
    },
    resetInOrOutForm() {
      this.$refs.formInOrOut.resetFields();
      //这里也是
      this.formInOrOut.id = '';
    },
    del(id) {
      console.log("要删除的用户id：" + id);
      this.$axios.get(this.$httpUrl + '/goods/del?id=' + id).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.loadPost()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    mod(row) {
      this.centerDialogVisible = true
      this.$nextTick(() => {//异步保证是给到编辑，而不是新增
        //可以简化
        // this.form=row;  //不能使用这个，`this.form` 变成了一个新的引用，指向了 `row` 对象的内存地址
        //赋值到表单
        this.form.id = row.id
        this.form.name = row.name
        this.form.storage = row.storage+''
        this.form.goodstype = row.goodstype+''
        this.form.count = row.count
        this.form.remark = row.remark
      })
    },
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm();
        //这里有问题
        //console.log("现可以出库最大量："+" "+this.form.name+this.form.id);
      })
    },
    inGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inOrOutDialogVisible = true
      this.$nextTick(() => {
        this.resetInOrOutForm();
      })

      this.formInOrOut.goodsname = this.currentRow.name
      this.formInOrOut.goods = this.currentRow.id
      this.formInOrOut.adminId = this.user.id
      this.formInOrOut.action='1';
    },
    outGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inOrOutDialogVisible = true
      this.$nextTick(() => {
        this.resetInOrOutForm();
      })
      this.formInOrOut.goodsname = this.currentRow.name
      this.formInOrOut.goods = this.currentRow.id
      this.formInOrOut.adminId = this.user.id
      this.max_outNum=this.currentRow.count;
      this.formInOrOut.action='2';
      console.log("现可以出库最大量："+this.max_outNum);
    },
    doMod() {
      this.$axios.post(this.$httpUrl + '/goods/update', this.form).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost();
          this.resetForm();
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    doSave() {
      this.$axios.post(this.$httpUrl + '/goods/save', this.form).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost();
          //写少了一条语句
          this.resetForm();
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //偶尔id不为空
          if (this.form.id) {
            this.doMod();
          } else {
            this.doSave();
          }
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    doInOrOutGoods() {
      this.$refs.formInOrOut.validate((valid) => {
        if (valid) {
          if(this.formInOrOut.action=='2'&&this.formInOrOut.count>this.max_outNum){
            this.max_outNum=10000;
            this.$message({
              message: '出库数量大于现有量！',
              type: 'error'
            });
            console.log('error submit!');
            return false;
          }
          this.$axios.post(this.$httpUrl + '/record/save', this.formInOrOut).then(res => res.data).then(res => {
            console.log(res)
            if (res.code == 200) {

              this.$message({
                message: '操作成功！',
                type: 'success'
              });
              this.inOrOutDialogVisible = false
              this.loadPost()
              this.resetInOrOutForm()
            } else {
              this.$message({
                message: '操作失败！',
                type: 'error'
              });
            }
          })
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1;
      this.pageSize = val;
      this.loadPost();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadPost();
    },
    resetParam() {
      this.name = '';
      this.storage='';
      this.goodstype='';
      this.loadPost();
    },
    loadPost() {
      this.$axios.post(this.$httpUrl + '/goods/listPage', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: {
          name: this.name,
          goodstype:this.goodstype+ '',
          storage:this.storage+ ''
          //这里原本是int，要转换成string
          // java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
        }
      }).then(res => res.data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.total = res.total;
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      });
    },
    loadStorage() {
      this.$axios.get(this.$httpUrl + '/storage/list').then(res => res.data).then(res => {
        if (res.code == 200) {
          this.storageData = res.data;
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      });
    },
    loadGoodstype() {
      this.$axios.get(this.$httpUrl + '/goodstype/list').then(res => res.data).then(res => {
        if (res.code == 200) {
          this.goodstypeData = res.data;
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      });
    }
  },
  beforeMount() {
    this.loadStorage();
    this.loadGoodstype();
    this.loadPost();
  }
}
</script>

<style scoped>

</style>